using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Helpers;
using AvalonAdmin.Pages.Rule.Views;
using AvalonAdminDto.Common;

using AvalonAdminDto.Rule.RuleConfigDtos;
using CommunityToolkit.Mvvm.Input;
using D.UtilCore.Dtos;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ursa.Controls;

namespace AvalonAdmin.Pages.Rule.ViewModels.RuleConfig
{
    /// <summary>
    /// 规则配置查询视图模型
    /// </summary>
    public class RuleConfigViewModel : SimpleIntegratedViewModel<RepRuleConfig>
    {
        #region 构造函数

        public RuleConfigViewModel()
        {
            LoadData();
        }

        #endregion

        #region 查询条件属性

        private string? _ruleKey;
        /// <summary>
        /// 规则唯一键
        /// </summary>
        public string? RuleKey
        {
            get => _ruleKey;
            set => SetProperty(ref _ruleKey, value);
        }

        private string? _no;
        /// <summary>
        /// 规则编号
        /// </summary>
        public string? No
        {
            get => _no;
            set => SetProperty(ref _no, value);
        }

        private bool _isSpecial = true;
        /// <summary>
        /// 是否特殊车位
        /// </summary>
        public bool IsSpecial
        {
            get => _isSpecial;
            set => SetProperty(ref _isSpecial, value);
        }

        #endregion

        #region 重写基类方法

        /// <summary>
        /// 重置查询条件
        /// </summary>
        public override void Reset()
        {
            RuleKey = string.Empty;
            No = string.Empty;
            IsSpecial = true;

            // 刷新数据
            LoadData();
        }

        #endregion

        #region 业务方法

        /// <summary>
        /// 规则映射
        /// </summary>
        private RelayCommand<RepRuleConfig>? _ruleMappingCommand;
        public RelayCommand<RepRuleConfig> RuleMappingCommand => _ruleMappingCommand ?? (_ruleMappingCommand = new RelayCommand<RepRuleConfig>(RuleMappingAction));

        protected async Task RuleMappingAction(RepRuleConfig? vm)
        {
            if (vm != null)
            {
                await Dialog.ShowModal<Page_RuleMapping_Query, RuleMappingQueryViewModel>(new RuleConfigModifyViewModel(vm.Id, ViewStatus.Edit), null, options: GetDialogOptions("规则映射"));
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        protected void Export(object? obj)
        {
        }

        #endregion

        #region 实现抽象方法

        public override async Task AddAsync(RepRuleConfig? obj = default)
        {
            var res = await Dialog.ShowModal<Page_RuleConfig_Modify, RuleConfigModifyViewModel>(
                new RuleConfigModifyViewModel(viewStatus: ViewStatus.Add), 
                null, 
                options: GetDialogOptions("添加规则配置"));
            
            if (res == DialogResult.OK)
            {
                await QueryAsync();
            }
        }

        public override async Task UpdateAsync(RepRuleConfig? obj = default)
        {
            var target = obj ?? SelectedModel;
            if (target == null)
            {
                ShowWarning("请选择要修改的数据");
                return;
            }

            var res = await Dialog.ShowModal<Page_RuleConfig_Modify, RuleConfigModifyViewModel>(
                new RuleConfigModifyViewModel(target.Id, ViewStatus.Edit), 
                null, 
                options: GetDialogOptions("修改规则配置"));
            
            if (res == DialogResult.OK)
            {
                await QueryAsync();
            }
        }

        public override async Task DeleteAsync(RepRuleConfig? obj = default)
        {
            var target = obj ?? SelectedModel;
            if (target == null)
            {
                ShowWarning("请选择要删除的数据");
                return;
            }

            var messageBoxResult = await MessageBox.ShowOverlayAsync(
                "确认删除该规则配置吗？", 
                "提示", 
                icon: MessageBoxIcon.Question, 
                button: MessageBoxButton.OKCancel);
            
            if (messageBoxResult == MessageBoxResult.OK)
            {
                var res = await HttpHelper<int>.DeleteAsync($"{ApiUrl.DeleteRuleConfig}/{target.Id}");
                if (res.Code == StatusCodeEnum.OK)
                {
                    ShowSuccess(res.Msg ?? "删除成功");
                    await QueryAsync();
                }
                else
                {
                    ShowError(res.Msg ?? "删除失败");
                }
            }
        }

        public override async Task BatchDeleteAsync(IEnumerable<RepRuleConfig>? items = null)
        {
            var selectedItems = items?.ToList() ?? Data?.Where(m => GetIsSelected(m)).ToList();
            if (selectedItems == null || !selectedItems.Any())
            {
                ShowWarning("请选择要删除的数据");
                return;
            }

            var messageBoxResult = await MessageBox.ShowOverlayAsync(
                $"确认删除选中的 {selectedItems.Count} 条规则配置吗？", 
                "提示", 
                icon: MessageBoxIcon.Question, 
                button: MessageBoxButton.OKCancel);
            
            if (messageBoxResult == MessageBoxResult.OK)
            {
                var ids = selectedItems.Select(m => m.Id).ToList();
                var res = await HttpHelper<int>.DeleteAsync($"{ApiUrl.DeleteRuleConfig}/{string.Join(",", ids)}");
                if (res.Code == StatusCodeEnum.OK)
                {
                    ShowSuccess(res.Msg ?? "批量删除成功");
                    await QueryAsync();
                }
                else
                {
                    ShowError(res.Msg ?? "批量删除失败");
                }
            }
        }

        protected override bool GetIsSelected(RepRuleConfig item)
        {
            return item.IsSelected;
        }

        protected override void SetIsSelected(RepRuleConfig item, bool isSelected)
        {
            item.IsSelected = isSelected;
        }

        public override async Task QueryAsync()
        {
            if (Data != null)
            {
                Data.Clear();
            }
            else
            {
                Data = new ObservableCollection<RepRuleConfig>();
            }

            var res = await HttpHelper<PageModel<RepRuleConfig>>.PostAsync(ApiUrl.QueryRuleConfigPages, new ReqQueryRuleConfigPage()
            {
                RuleKey = RuleKey,
                No = No,
                PageSize = PageSize,
                PageNo = PageNo
            });

            if (res.Code == StatusCodeEnum.Warning)
            {
                ShowWarning(res.Msg);
            }
            else if (res.Code == StatusCodeEnum.Error)
            {
                ShowError(res.Msg);
            }
            else if (res.Code == StatusCodeEnum.ServerError)
            {
                ShowError("服务器异常");
            }
            else if (res.Code == StatusCodeEnum.OK)
            {
                if (res.Data != null)
                {
                    foreach (var item in res.Data.Data)
                    {
                        item.IsSelected = false;
                        Data.Add(item);
                    }

                    TotalCount = res.Data.TotalCount;
                    TotalPage = res.Data.TotalPage;

                    base.RefPage();
                }
            }
            else
            {
                ShowError(res.Code.ToString());
            }
        }

        #endregion

    }
}



